package com.hup.sokoban.view.winning;

import com.hup.sokoban.service.common.AudioService;
import com.hup.sokoban.view.main.MainFrame;
import com.hup.utils.commons.start.SpringContext;
import com.hup.utils.swing.FrameUtil;
import com.hup.utils.swing.frame.BaseDialog;
import com.hup.utils.swing.frame.SingletonWindowHelper;
import lombok.extern.log4j.Log4j2;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;

/**
 * 通关窗口;
 * .有背景音乐
 *
 * @author hugan
 * @date 2020/5/26
 */
@Log4j2
public class WinningDialog extends BaseDialog {

    private final AudioService audioService;
    private WinningWindowForm form;
    private MainFrame formWindow;

    public static void showFrame(MainFrame formWindow) {
        WinningDialog dialog = SingletonWindowHelper.getWindow(WinningDialog.class);
        if (dialog == null) {
            dialog = new WinningDialog(formWindow);
        }
        dialog.setVisible(true);
    }

    private WinningDialog(MainFrame formWindow) {
        super("通关了!");
        this.formWindow = formWindow;
        audioService = SpringContext.getBean(AudioService.class);
        initView();
        initListener();
    }

    private void initView() {
        form = new WinningWindowForm();
        setContentPane(form.root);
        scaleGif();

        FrameUtil.setTransparent(this);
        setResizable(false);
        pack();
        setLocationRelativeTo((Component) formWindow);
        setEscapeCancelable(true);
    }

    /**
     * 按父窗口一半高度,缩放gif
     */
    private void scaleGif() {
        ImageIcon icon = (ImageIcon) form.lab.getIcon();
        Image image = icon.getImage();
        double ratio = image.getWidth(null) / (image.getHeight(null) + 0d);
        Window parent = (Window) formWindow;
        Image scaledInstance = image.getScaledInstance((int) (ratio * parent.getHeight() / 2), parent.getHeight() / 2, Image.SCALE_DEFAULT);
        icon.setImage(scaledInstance);
    }

    private void initListener() {
        form.btnEsc.setActionListener(e -> onCancel());
        form.btnNextMap.setActionListener(e -> pressedNextMap());
        ((JComponent) getContentPane()).registerKeyboardAction(e -> pressedNextMap(),
                KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);
    }

    @Override
    public void onShown() {
        audioService.playWinning();
    }

    @Override
    public void onHidden(boolean dispose) {
        log.debug("");
        formWindow = null;
        audioService.stopWinning();
    }

    private void pressedNextMap() {
        dispose();
        formWindow.wonAndToNextMap();
    }

}
